
/**
 * 获取RefreshToken
 * @description: 创建新的请求实例实现
 */
import { createAlova } from 'alova'
import { useAccessStore } from '@vben/stores';
import fetchAdapter from 'alova/fetch';
import vueHook from 'alova/vue';
import { getBaseURL, ACCESS_TOKEN_FIELD } from './config';

let lock = false
let promiseResult: any[] = []

const alova = createAlova({
  baseURL: getBaseURL(),
  cacheFor: null,
  statesHook: vueHook,
  requestAdapter: fetchAdapter(),
  beforeRequest: (method) => {
    // ...原请求前拦截器
    const accessStore = useAccessStore();

    // const userStore = useUserStore()
    // console.log('beforeRequest', userStore.accessToken)
    // 添加token到请求头
    // method.config.headers[ACCESS_TOKEN_FIELD] = `${userStore.accessToken}`
  },
  responded: async (response, method) => {
    let json = await response.json();
    return json.data || null
  },
})

export function getAccessToken(rToken: string): Promise<any> {
  return new Promise(async (resolve, reject) => {
    promiseResult.push({
      resolve,
      reject
    })
    // const userStore = useUserStore();

    if (!lock) {
      lock = true
      // 为了让refreshToken请求顺利通过，需要通过元数据标识authRole为refreshToken。参考官方文档
      const method = alova.Post('/system/auth/refreshToken', { token: rToken }, {
        meta: {
          authRole: 'refreshToken'
        }
      });
      method.send()
        .then((data: any) => {
          console.log(data)
          // 如果 refreshToken 请求成功，则将新的token存储到本地
          if (data && data.accessToken) {
            // userStore.setToken(data.accessToken);
            // userStore.setTokenExpiresTime(data.accessExpire)
            // userStore.setRefreshToken(data.refreshToken);
            while (promiseResult.length) {
              // p1.resolve(res.data)
              promiseResult.shift().resolve(data)
            }
            lock = false
            return
          }
          // userStore.resetStore()
          while (promiseResult.length) {
            // p1.reject(err)
            promiseResult.shift().reject("身份认证已失效，请重新登录")
          }

        })
        .catch(err => {
          while (promiseResult.length) {
            // p1.reject(err)
            promiseResult.shift().reject(err)
          }
          lock = false
        })
    }

  })
}
